<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入合同名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择销售类型" clearable>
          <el-option v-for="dict in dict.type.contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:contract:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:contract:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:contract:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:contract:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同ID" align="center" prop="id" />
      <el-table-column label="合同名称" align="center" prop="name" />
      <el-table-column label="事业部名称" align="center" prop="businessName" />
      <el-table-column label="交付部名称" align="center" prop="deliverName" />
      <el-table-column label="客户" align="center" prop="customerName" />
      <el-table-column label="销售类型" align="center" prop="sellType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sell_type" :value="scope.row.sellType" />
        </template>
      </el-table-column>
      <el-table-column label="付费模式信息" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_type_info" :value="scope.row.payType" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:contract:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:contract:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择合同类型" style="width: 100%;">
                <el-option v-for="dict in dict.type.contract_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="事业部" prop="businessId">
              <el-select v-model="form.businessId" placeholder="请选择合同类型" style="width: 100%;">
                <el-option v-for="dict in businessOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付部" prop="deliverId">
              <el-select v-model="form.deliverId" placeholder="请选择合同类型" style="width: 100%;">
                <el-option v-for="dict in deliverydeptOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售类型" prop="sellType">
              <el-select v-model="form.sellType" placeholder="请选择销售类型" style="width: 100%;">
                <el-option v-for="dict in dict.type.sell_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付费模式信息" prop="payType">
              <el-select v-model="form.payType" placeholder="请选择付费模式信息" style="width: 100%;">
                <el-option v-for="dict in dict.type.pay_type_info" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">付费模式明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddContractPayDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteContractPayDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="contractPayDetailList" :row-class-name="rowContractPayDetailIndex"
          @selection-change="handleContractPayDetailSelectionChange" ref="contractPayDetail" style="width: 100%;">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="地域名称" prop="areaName">
            <template slot-scope="scope">
              <el-select v-model="scope.row.areaId" placeholder="请输入地域名称">
                <el-option v-for="dict in areaOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="岗位名称" prop="postName">
            <template slot-scope="scope">
              <el-select v-model="scope.row.postId" placeholder="请输入岗位名称">
                <el-option v-for="dict in postOptions" :key="dict.postId" :label="dict.postName"
                  :value="parseInt(dict.postId)"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="职级" prop="postRank">
            <template slot-scope="scope">
              <el-select v-model="scope.row.postRank" placeholder="请选择职级" clearable>
                <el-option v-for="dict in dict.type.customer_post_rank" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="GP1%目标值（%）" prop="gp1TargetValue">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.gp1TargetValue" :controls="false" :precision="2" style="width:100%"
                placeholder="请输入GP1%目标值" />
            </template>
          </el-table-column>
          <el-table-column label="结算价（元）" prop="settPrice">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.settPrice" :controls="false" :precision="2" style="width:100%"
                placeholder="请输入结算价" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContract, getContract, delContract, addContract, updateContract, listBussinessdeptApi, listDeliverydeptApi, listAreaApi, listPostApi } from "@/api/system/contract";

export default {
  name: "Contract",
  dicts: ['pay_type_info', 'sell_type', 'contract_type', 'customer_post_rank'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedContractPayDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同表格数据
      contractList: [],
      // 付费模式明细表格数据
      contractPayDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        businessId: null,
        type: null,
        deliverId: null,
        customerName: null,
        sellType: null,
        payType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "合同类型不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "事业部不能为空", trigger: "change" }
        ],

        deliverId: [
          { required: true, message: "交付部不能为空", trigger: "change" }
        ],
        customerName: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        sellType: [
          { required: true, message: "销售类型不能为空", trigger: "change" }
        ],
        payType: [
          { required: true, message: "付费模式信息不能为空", trigger: "change" }
        ]
      },
      businessOptions: [],
      deliverydeptOptions: [],
      areaOptions: [],
      postOptions: []
    };
  },
  created () {
    this.initOptions()
    this.getList();
  },
  methods: {
    /** 查询配置项 */
    initOptions () {
      listBussinessdeptApi().then(res => {
        this.businessOptions = res.data
      })
      listDeliverydeptApi().then(res => {
        this.deliverydeptOptions = res.data
      })
      listAreaApi().then(res => {
        this.areaOptions = res.data
      })
      listPostApi().then(res => {
        this.postOptions = res.data
      })
    },
    /** 查询合同列表 */
    getList () {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        type: null,
        name: null,
        businessId: null,
        businessName: null,

        deliverId: null,

        deliverName: null,
        customerName: null,
        sellType: null,
        payType: null
      };
      this.contractPayDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加合同";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.contractPayDetailList = response.data.contractPayDetailList;
        this.$nextTick(() => {
          this.open = true;
        })
        this.title = "修改合同";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.contractPayDetailList = this.contractPayDetailList;
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同编号为"' + ids + '"的数据项？').then(function () {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 付费模式明细序号 */
    rowContractPayDetailIndex ({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 付费模式明细添加按钮操作 */
    handleAddContractPayDetail () {
      let obj = {};
      obj.areaName = "";
      obj.areaId = "";
      obj.postId = "";
      obj.postName = "";
      obj.postRank = "";
      obj.gp1TargetValue = "";
      obj.
        settPrice = "";
      this.contractPayDetailList.push(obj);
    },
    /** 付费模式明细删除按钮操作 */
    handleDeleteContractPayDetail () {
      if (this.checkedContractPayDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的付费模式明细数据");
      } else {
        const contractPayDetailList = this.contractPayDetailList;
        const checkedContractPayDetail = this.checkedContractPayDetail;
        this.contractPayDetailList = contractPayDetailList.filter(function (item) {
          return checkedContractPayDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleContractPayDetailSelectionChange (selection) {
      this.checkedContractPayDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
